package com.android.manghe.mine.fragment

import android.graphics.Rect
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.base.frame.extend.IRefresh
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPFragment
import com.android.base.tools.*
import com.android.base.tools.Glide.GlideHelper
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.config.events.*
import com.android.manghe.mine.activity.*
import com.android.manghe.mine.adapter.MineOrderMenuAdapter
import com.android.manghe.mine.model.InviteStatisticsRes
import com.android.manghe.mine.model.UserDetailRes
import com.android.manghe.mine.model.UserRes
import com.android.manghe.mine.presenter.PMine
import com.android.manghe.user.activity.LoginActivity
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import com.meiqia.meiqiasdk.util.MQIntentBuilder
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.fragment_mine.*
import java.util.*

class MineFragment : MVPFragment<PMine>(), View.OnClickListener, IRefresh {
    private var userInfo: UserRes.UserInfo? = null
    private val orderTitle = arrayListOf("免单中", "待付款", "待发货", "待收货", "退货/售后", "已完成")
    private val orderIconRes = arrayListOf(
        R.mipmap.mian_dan, R.mipmap.wait_pay, R.mipmap.wait_send,
        R.mipmap.wait_receive, R.mipmap.tuikuan_shouhou, R.mipmap.order_complete
    )

    override fun getLayoutId() = R.layout.fragment_mine
    override fun showToolBarType() = ETitleType.OVERLAP_TITLE
    override fun initData(savedInstanceState: Bundle?, parent: View) {
        initListener()
        refreshView()
    }

    private fun initListener() {
        tvRealNameAuth.setOnClickListener(this)
        ivAvatar.setOnClickListener(this)
        ivNick.setOnClickListener(this)
        tvReceivingAddress.setOnClickListener(this)
        ivMsg.setOnClickListener(this)
        ivSetting.setOnClickListener(this)
        tvBigPan.setOnClickListener(this)
        tvMyGroup.setOnClickListener(this)
        tvService.setOnClickListener(this)
        tvInviteShare.setOnClickListener(this)
        layoutCommission.setOnClickListener(this)
        layoutIntegral.setOnClickListener(this)
        layoutBoxCoin.setOnClickListener(this)
        layoutGiftCoin.setOnClickListener(this)
        tvAllOrder.setOnClickListener(this)
        tvInviteAll.setOnClickListener(this)
        tvWaitPay.setOnClickListener(this)
        tvWaitSend.setOnClickListener(this)
        tvWaitReceive.setOnClickListener(this)
        tvOrderComplete.setOnClickListener(this)
        tvMyCommission.setOnClickListener(this)
        tvFeedBack.setOnClickListener(this)
        tvSign.setOnClickListener(this)
        tvWithdrawal.setOnClickListener(this)
        tvTopUp.setOnClickListener(this)
        Bus.observe<UserRes.UserInfo>().subscribe {
            refreshView()
        }.registerInBus(this)
        Bus.observe<RefreshUserInfoEvent>().subscribe {
            refreshView()
        }.registerInBus(this)
        Bus.observe<RefreshMemberInfoEvent>().subscribe {
            onResume()
        }.registerInBus(this)
        Bus.observe<RefreshMsgCountEvent>().subscribe {
            userInfo = UserHolder.getUserInfo(activity?.applicationContext)
            if (userInfo != null) {
                p.getMsgCount(userInfo!!.UID, userInfo!!.TOKEN)
            }
        }.registerInBus(this)
        val layoutParam = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        layoutParam.topMargin = StatusBarUtil.getStatusBarHeight(activity)
        layoutTop.layoutParams = layoutParam

        //订单
        val gridLayoutManager =
            GridLayoutManager(activity, 1, LinearLayoutManager.HORIZONTAL, false)
        orderRecyclerView.layoutManager = gridLayoutManager
        val orderAdapter = MineOrderMenuAdapter(
            orderTitle, orderIconRes,
            (ScreenUtil.getScreenWidth(activity) - DisplayUtil.dip2px(activity, 24f)) / 5
        )
        orderRecyclerView.adapter = orderAdapter
        orderAdapter.setOnItemClickListener { adapter, view, position ->
            open(MyOrderActivity::class.java, mapOf("position" to position))
        }
        orderSeekBar.setPadding(0, 0, 0, 0)
        orderSeekBar.thumbOffset = 0
        orderRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                //显示区域的高度。
                val extent: Int = orderRecyclerView.computeHorizontalScrollExtent()
                //整体的高度，注意是整体，包括在显示区域之外的。
                val range: Int = orderRecyclerView.computeHorizontalScrollRange()
                //已经向下滚动的距离，为0时表示已处于顶部。
                val offset: Int = orderRecyclerView.computeHorizontalScrollOffset()
                //此处获取seekbar的getThumb，就是可以滑动的小的滚动游标
                val gradientDrawable = orderSeekBar.thumb as GradientDrawable
                //根据列表的个数，动态设置游标的大小，设置游标的时候，progress进度的颜色设置为和seekbar的颜色设置的一样的，所以就不显示进度了。
                gradientDrawable.setSize(
                    DisplayUtil.dip2px(activity, 26f),
                    DisplayUtil.dip2px(activity, 3f)
                ) //extent / (commentAdapterFenLei.getData().size() / 2)
                //设置可滚动区域
                orderSeekBar.max = (range - extent)
                when {
                    dx == 0 -> {
                        orderSeekBar.progress = 0
                    }
                    dx > 0 -> {
                        orderSeekBar.progress = offset
                    }
                    dx < 0 -> {
                        orderSeekBar.progress = offset
                    }
                }
            }
        })

        userInfo = UserHolder.getUserInfo(activity?.applicationContext)
        if (userInfo != null) {
            p.getMsgCount(userInfo!!.UID, userInfo!!.TOKEN)
        }
    }

    override fun onResume() {
        super.onResume()
        userInfo = UserHolder.getUserInfo(activity?.applicationContext)
        if (userInfo != null) {
            p.getUserDetail(userInfo!!.UID, userInfo!!.TOKEN)//获取用户中心的数据
            p.getFeedBackMsgCount(userInfo!!.UID, userInfo!!.TOKEN)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    override fun onClick(v: View?) {
        if (UserHolder.getUserInfo(activity) == null) {
            LoginActivity.showActivity(activity!!)
        } else {
            if (v == ivAvatar || v == ivNick) {
                //头像，昵称
                open(MyMsgActivity::class.java)
            } else if (v == ivMsg) {
                //消息
                open(MsgActivity::class.java)
            } else if (v == tvBigPan) {
                //大转盘
                BigLuckDrawActivity.showActivity(activity!!)
            } else if (v == tvMyCommission) {
                //佣金明细
                val totalCommission = tvCommission.text.toString()
                open(
                    CommissionDetailActivity::class.java,
                    mapOf("totalCommission" to totalCommission)
                )
            } else if (v == tvSign) {
                //签到
                p.userDetail?.let {
                    open(SignActivityBak::class.java)
                }
            } else if (v == tvRealNameAuth) {
                //实名认证

            } else if (v == tvMyGroup) {
                //我的团队
                open(MyTeamActivity::class.java)
            } else if (v == tvAllOrder) {
                //全部订单
                open(MyOrderActivity::class.java)
            } else if (v == tvInviteShare) {
                //邀请分享
                open(ShareActivity::class.java)
            } else if (v == tvReceivingAddress) {
                //收货地址
                open(AddressListActivity::class.java)
            } else if (v == tvService) {
                //客服中心
                val userInfo = UserHolder.getUserInfo(activity)
//                userInfo?.let {
//                    val clientInfo = HashMap<String, String>();
//                    clientInfo.put("mid", it.UID);
//                    clientInfo.put("nickName", it.nickname);
//                    clientInfo.put("avatar", it.avatar);
//                    startActivity(
//                        MQIntentBuilder(activity)
//                            .setClientInfo(clientInfo) // 设置顾客信息 PS: 这个接口只会生效一次,如果需要更新顾客信息,需要调用更新接口
//                            .build()
//                    );
//                }
                userInfo?.let {
                    p.set53(activity, userInfo)
                }
//                open(CustomerServiceActivity::class.java)
            } else if (v == ivSetting) {
                //设置
                SettingActivity.showActivity(activity!!)
            } else if (v == tvWaitPay) {
                //待付款
                //open(MyOrderActivity::class.java, mapOf("position" to 1))
            } else if (v == tvWaitSend) {
                //待发货
                open(MyOrderActivity::class.java, mapOf("position" to 1))
            } else if (v == tvWaitReceive) {
                //待收货
                open(MyOrderActivity::class.java, mapOf("position" to 2))
            } else if (v == tvOrderComplete) {
                //已完成
                open(MyOrderActivity::class.java, mapOf("position" to 3))
            } else if (v == tvWithdrawal) {
                //提现
                val commission = tvCommission.text.toString().toFloat()
                if (commission == 0f) {
                    ToastUtil.showLong(activity, "您没有可提现佣金")
                    return
                }
                open(WithdrawalActivity::class.java, mapOf("commission" to commission))
            } else if (v == tvFeedBack) {
                //投诉建议
                open(FeedbackActivity::class.java)
            } else if (v == layoutIntegral) {
                //积分页面
                open(
                    CoinAndIntegralDetailActivity::class.java,
                    hashMapOf<String, Any>(
                        "definite" to tvIntegral.text.toString(),
                        "position" to 2
                    )
                )
            } else if (v == tvTopUp) {
                //支付页面
                open(TopUpActivity::class.java)
            } else if (v == tvInviteAll) {
                //邀请页面
                open(InviteActivity::class.java)
            } else if (v == layoutBoxCoin) {
                //开盒币详细页面
                open(
                    CoinAndIntegralDetailActivity::class.java,
                    hashMapOf<String, Any>("definite" to tvMyBi.text.toString(), "position" to 0)
                )
            } else if (v == layoutGiftCoin) {
                //赠币的详细页面
                open(
                    CoinAndIntegralDetailActivity::class.java,
                    hashMapOf<String, Any>("definite" to tvGiftBi.text.toString(), "position" to 1)
                )
            }
        }
    }

    override fun getRefreshView(): SmartRefreshLayout {
        return mView.findViewById(R.id.refreshLayout)
    }

    override fun onRefresh() {
        refreshView()
    }

    override fun onLoad() {

    }

    private fun refreshView() {
        userInfo = UserHolder.getUserInfo(activity?.applicationContext)
        if (userInfo != null) {
            p.getUserDetail(userInfo!!.UID, userInfo!!.TOKEN)
            p.getMsgCount(userInfo!!.UID, userInfo!!.TOKEN)
            p.getInviteStatistics(userInfo!!.UID, userInfo!!.TOKEN)
        } else {
            ivAvatar.setImageResource(R.mipmap.user_normal)
            ivNick.text = "登录/注册"
            ivMsgDot.visibility = View.GONE
            tvCommission.text = "0"
            tvMyBi.text = "0.00"
            tvGiftBi.text = "0.00"
            tvIntegral.text = "0"
        }
    }

    fun updateUserDetail(userDetail: UserDetailRes.UserDetail) {
        userInfo?.nickname = userDetail.nickname
        userInfo?.avatar = userDetail.photo
        userInfo?.UID = userDetail.mid

        //针对小米审核无法通过的判断
        if(userDetail.mid.equals("911766")){
            lyInvite.visibility=View.GONE;
            tvInviteShare.visibility=View.GONE
            tvFeedBack.visibility=View.GONE
        }else{
            lyInvite.visibility=View.VISIBLE;
            tvInviteShare.visibility=View.VISIBLE
            tvFeedBack.visibility=View.VISIBLE
        }

        tvMyBi.text =
            if (userDetail.coin != null && !TextUtils.equals(
                    "false",
                    userDetail.coin
                )
            ) userDetail.coin else "0.00"
        tvGiftBi.text = if (userDetail.free_coin != null) userDetail.free_coin else "0.00"
        tvIntegral.text = if (userDetail.score != null) userDetail.score else "0"

        ivNick.text = userInfo!!.nickname
        val finaluserAvatar =
            ConstantsUrl.host + "/upload/1/images/photo/" + userDetail.mid + "_src.png"
        val avatar =
            if (TextUtils.isEmpty(userInfo?.avatar)) finaluserAvatar else userInfo?.avatar
        GlideHelper.loadAvatar(activity, avatar, ivAvatar)

        userInfo = UserHolder.getUserInfo(activity)
        userInfo?.let {
            it.nickname = userDetail.nickname
            it.avatar = userDetail.photo
            it.UID = userDetail.mid
            it.sex = userDetail?.sex
            it.nickname = userDetail?.nickname
            it.mobile = userDetail?.mobile
            UserHolder.setUserInfo(activity, it)
        }
    }

    fun updateMsgDot(isShow: Boolean) {
        ivMsgDot.visibility = if (isShow) View.VISIBLE else View.GONE
        // Bus.send(ShowTabMsgRedDotEvent(isShow))
    }


    fun updateInviteStatistics(inviteBean: InviteStatisticsRes.DataBean) {
        tvAllInviteCount.text = "${inviteBean.invite_num}"
        tvCommission.text = "${inviteBean.remain}"
    }

    fun setFeedbackDot(isShowDot: Boolean) {
        var normalFeedbackDrawable =
            ContextCompat.getDrawable(activity!!, R.mipmap.mine_fun_feed_back)
        var dotFeedbackDrawable =
            ContextCompat.getDrawable(activity!!, R.mipmap.mine_fun_feed_back_dot)
        normalFeedbackDrawable!!.bounds = Rect(
            0,
            0,
            normalFeedbackDrawable!!.intrinsicWidth,
            normalFeedbackDrawable!!.intrinsicHeight
        )
        dotFeedbackDrawable!!.bounds = Rect(
            0,
            0,
            dotFeedbackDrawable!!.intrinsicWidth,
            dotFeedbackDrawable!!.intrinsicHeight
        )
        tvFeedBack.setCompoundDrawables(
            null,
            if (isShowDot) dotFeedbackDrawable else normalFeedbackDrawable,
            null,
            null
        )
    }
}
